package latihan.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Logger;

public class LoginManager {
	public Logger log = Logger.getLogger(LoginManager.class.getName());
	
	 private Connection connect = null;
  	 private PreparedStatement preparedStatement = null;
  	 private ResultSet resultSet = null;
	
  	 private String screenName;
  	 
  	 
  	 public String doConnect(String name, String password){
  		log.info(name+" ---- "+password);
  		try {
			Class.forName("com.mysql.jdbc.Driver");
			connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/coba?user=root");
			log.info("connect");
		    // Result set get the result of the SQL query
		    preparedStatement = connect.prepareStatement("select * from logintest where user_name = ? AND password = ?");
		    preparedStatement.setString(1, name);
		    preparedStatement.setString(2, password);
		    resultSet = preparedStatement.executeQuery();
		    writeResultSet(resultSet);
		} catch (ClassNotFoundException e) {
			log.info("kelas hilang");
			e.printStackTrace();
		}
  			// Setup the connection with the DB
  			catch (SQLException e) {
  			log.info("db tidak ada");
			e.printStackTrace();
		}
		return screenName;
        
  	 }
  	 
  	private void writeResultSet(ResultSet resultSet) throws SQLException {
  	    // ResultSet is initially before the first data set
  	    while (resultSet.next()) {
  	      // It is possible to get the columns via name
  	      // also possible to get the columns via the column number
  	      // which starts at 1
  	      // e.g. resultSet.getSTring(2);
  	    	screenName = resultSet.getString("screen_name");
  	    }
  	  }

	public boolean doRegister(String name, String password, String userId) {
		Boolean result = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/coba?user=root");
			log.info("connect");
		    // Result set get the result of the SQL query
		    preparedStatement = connect.prepareStatement("insert into logintest(user_name, password, screen_name) values (?, ?, ?");
		    preparedStatement.setString(1, userId);
		    preparedStatement.setString(2, password);
		    preparedStatement.setString(3, name);
		    result = preparedStatement.execute();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (SQLException e) {
  			log.info("db tidak ada");
			e.printStackTrace();
		}
		
		return result;
	}
	
}
